package com.ruoyi.project.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class HHAuthUtils {

    // 百度身份认证
    @Autowired
    private RedisUtils redisUtils;

    private String AKI = "ZcD0hBA27cZHRIOCUjDCN1ha";

    private String AKS = "5GI8cnYGSYeIMCH8a6U91Wv2hrBzOOuv";

    public String getAccessToken () throws Exception {
        String token = this.redisUtils.get("DLG_OCR_TOKEN");
        if (token == null) {
            String link = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + this.AKI + "&client_secret=" + this.AKS + "&";
            URL url = new URL(link);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("connection", "keep-alive");
            connection.setRequestMethod("POST");
            connection.connect();
            BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String result = "";
            while ((line = read.readLine()) != null) {
                result += line;
            }
            token = JSON.parseObject(result).get("access_token").toString();
            this.redisUtils.set("DLG_OCR_TOKEN", token, 43200);
        }
        return token;
    }

    public Object doAuth (String imgUrl) throws Exception {
        String token = this.getAccessToken();

        String path = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.addHeaderParameter("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        request.addQueryParameter("access_token", token);
        String jsonBody = "url=" + imgUrl + "&id_card_side=front&detect_photo=true&detect_quality=true";
        request.setJsonBody(jsonBody);
        try {
            ApiExplorerClient client = new ApiExplorerClient();
            ApiExplorerResponse response = client.sendRequest(request);
            JSONObject jsonObject = JSON.parseObject(response.getResult());
            this.checkImageStatus(jsonObject.getString("image_status"));
            this.checkIdcardNumberType(jsonObject.getInteger("idcard_number_type"));
            this.checkQuality(jsonObject.getJSONObject("card_quality"));
            JSONObject json = jsonObject.getJSONObject("words_result");
  /*          UserDetailAuthObj authObj = new UserDetailAuthObj();
            authObj.setAddress(json.getJSONObject("住址").getString("words"));
            authObj.setBirthDate(json.getJSONObject("出生").getString("words"));
            authObj.setGender(json.getJSONObject("性别").getString("words"));
            authObj.setIDNumber(json.getJSONObject("公民身份号码").getString("words"));
            authObj.setName(json.getJSONObject("姓名").getString("words"));
            authObj.setNationality(json.getJSONObject("民族").getString("words"));
            authObj.setAvatar(JSON.parseObject(response.getResult()).getString("photo"));*/
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private void checkImageStatus (String imageStatus) {
        switch (imageStatus) {
            case "normal":
                break;
            case "reversed_side":
                throw new RuntimeException("身份证正反面颠倒");
            case "non_idcard":
                throw new RuntimeException("上传的图片中不包含身份证");
            case "blurred":
                throw new RuntimeException("身份证模糊");
            case "other_type_card":
                throw new RuntimeException("其他类型证照");
            case "over_exposure":
                throw new RuntimeException("身份证关键字段反光或过曝");
            case "over_dark":
                throw new RuntimeException("身份证欠曝（亮度过低）");
            case "unknown":
                throw new RuntimeException("识别失败：错误");
            default:
                throw new RuntimeException("未知识别类型");
        }
    }

    /*
    - 1： 身份证正面所有字段全为空
    0： 身份证证号不合法，此情况下不返回身份证证号
    1： 身份证证号和性别、出生信息一致
    2： 身份证证号和性别、出生信息都不一致
    3： 身份证证号和出生信息不一致
    4： 身份证证号和性别信息不一致
     */
    private void checkIdcardNumberType (Integer type) {
        switch (type) {
            case 1:
                break;
            default:
                throw new RuntimeException("未知识别类型");
        }
    }

    /*
    IsClear - 是否清晰；
    IsComplete - 是否边框/四角完整；
    IsNoCover - 是否头像、关键字段无遮挡/马赛克。
    及对应的概率：IsComplete_propobility、IsNoCover_propobility、IsClear_propobility，值在0-1之间，值越大表示图像质量越好。
    默认阈值：当 IsComplete_propobility 超过0.5时，IsComplete返回1，低于0.5，则返回0。IsNoCover_propobility、IsClear_propobility 同上
     */
    private void checkQuality (JSONObject quality) {
        Integer isNoCover = quality.getInteger("IsNoCover");
        //        Integer isClear = quality.getInteger("IsClear");
        Integer isComplete = quality.getInteger("IsComplete");
        Double isClearPropobility = quality.getDouble("IsClear_propobility");
        if (isNoCover == null || 0 == isNoCover) {
            throw new RuntimeException("请确认头像、关键字段无遮挡/马赛克");
        }
        //        if (isClear == null || 0 == isNoCover) {
        //            throw new RuntimeException("照片清晰度过低");
        //        }
        if (isComplete == null || 0 == isComplete) {
            throw new RuntimeException("请确认边框/四角完整");
        }
        if (isClearPropobility == null || isClearPropobility < 0.69D) {
            throw new RuntimeException("照片清晰度过低");
        }

    }

    public static void main (String[] args) throws Exception {
        String AKI = "ZcD0hBA27cZHRIOCUjDCN1ha";

        String AKS = "5GI8cnYGSYeIMCH8a6U91Wv2hrBzOOuv";
        String token = null;
        if (token == null) {
            String link = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + AKI + "&client_secret=" + AKS + "&";
            URL url = new URL(link);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("connection", "keep-alive");
            connection.setRequestMethod("POST");
            connection.connect();
            BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String result = "";
            while ((line = read.readLine()) != null) {
                result += line;
            }
            token = JSON.parseObject(result).get("access_token").toString();
        }
    }

}
